/**
 * @desc 请求封装
 * @auth 韩
 */

// import ZCNotification from "@/component/ZCNotification/zcnotification";
import axios from "axios";
import { getUrlParam } from "./getUrlData";

let baseUrl = process.env.REACT_APP_BASE_URL;

// 创建axios实例 ，设置默认请求配置
const instance = axios.create({
    timeout: 60000,//超时时间
    baseURL: baseUrl//基本路由
})

//统一设置post请求头
instance.defaults.headers.post['Content-Type'] = "application/json";

// 如果你是上传文件的话需要设置为
// instance.defaults.headers.post['Content-Type'] = 'multipart/form-data';


//请求拦截器
instance.interceptors.request.use(config => {
    // var token = sessionStorage.token;//获取缓存中的token
    config.headers['Authentication'] = getUrlParam("auth");//在请求头中加上token
    // if (token) {
    //     config.headers['Authentication'] = getUrlParam("auth");//在请求头中加上token
    // }

    return config;
}, error => {
    return Promise.reject(error)
})


// 响应拦截 判断数据是否正常完好，再把数据返回到发请求的地方
instance.interceptors.response.use(response => {
    // console.log("响应拦截处：\n", response)
    if (response.status === 200) {
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response.data.msg)
    }
}, error => {
    //请求报错的回调，对不同状态码进行处理
    if (error.response) {
        if (error.response.status === 401) {
            this.props.history.push("/login");//跳转回到登录页面
        }
        return Promise.reject(error)
    } else {
        return Promise.reject("请求超时，请重试");
    }
})


// 封装get请求
export const get = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: "get",
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}






//封装post请求
export const post = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch((error) => {
            console.log('post封装：', error)
            reject(error)
            // ZCNotification({ text: error, type: "error" })
        })
    })
}
